package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
  @Autowired
  private OrderMapper orderMapper;
  @Scheduled(cron = "0 * * * * ?")
    public void ordretimetask(){
     LocalDateTime time= LocalDateTime.now().plusMinutes(-15);
    List<Orders>ordersList= orderMapper.getstatusandordertime(Orders.PENDING_PAYMENT,time);
    if(ordersList !=null && ordersList.size()>0){
      for (Orders orders : ordersList) {
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("订单支付超时，自动取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
      }
    }
  }
  @Scheduled(cron = "0 0 1 * * ?")
  public void orderfinish(){
    LocalDateTime time =LocalDateTime.now().plusHours(-1);
    List<Orders>ordersList= orderMapper.getstatusandordertime(Orders.DELIVERY_IN_PROGRESS,time);
    if(ordersList !=null && ordersList.size()>0){
      for (Orders orders : ordersList) {
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
      }
    }
  }
  @Scheduled(cron = "0 * * * * ?")
  public void ordrevoertimetask() {
    // 获取当前时间并减去30分钟
    LocalDateTime time = LocalDateTime.now().plusMinutes(-30);

    // 从数据库中获取30分钟前接单且状态为待配送的订单列表
    List<Orders> ordersList = orderMapper.getstatusandordertime(Orders.CONFIRMED, time);

    // 判断是否有符合条件的订单
    if (ordersList != null && ordersList.size() > 0) {
      // 遍历订单列表，将每个订单的状态设为取消，设置取消原因和取消时间
      for (Orders orders : ordersList) {
        orders.setStatus(Orders.CANCELLED); // 设置订单状态为取消
        orders.setPayStatus(2);//设置订单支付状态为已取消
        orders.setCancelReason("骑手不足无法配送，自动取消"); // 设置取消原因
        orders.setCancelTime(LocalDateTime.now()); // 设置取消时间为当前时间

        // 更新订单信息到数据库
        orderMapper.update(orders);
      }
    }
  }


}
